package com.lyy.security.filter;

import com.lyy.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 验证请求携带的token是否有效
 */
@Component
public class TokenVerifyFilter extends GenericFilterBean {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            //从请求头中获取token
            String token = request.getHeader("Authorization-Token");
            if (StringUtils.hasText(token)) {
                //从token中解析用户名
                String username = JwtUtils.getUserInfo(token);
                //查询当前用户
                if(!StringUtils.isEmpty(username)){
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    if(null!=userDetails){
                        //查询不到表示用户不存在
                        //从token中获取用户信息封装成 UsernamePasswordAuthenticationToken
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(token, "", userDetails.getAuthorities());
                        //设置用户信息
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }
            }
        } catch (Exception e) {
            //登录发生异常,但要继续走其余过滤器的逻辑
            e.printStackTrace();
        }
         //继续执行springsecurity的过滤器
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
